package com.cmsz.uregs.controllers;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.cmsz.uregs.entity.Admin;
import com.cmsz.uregs.service.AdminService;

@RestController
public class AdminController {
	@Autowired
	private AdminService adminService;

	@RequestMapping(value = "admin", method = RequestMethod.GET)
	public List<Admin> findAllAdmins() {
		return adminService.findAllAdmins();
	}

	@RequestMapping(value = "admin", method = RequestMethod.POST)
	public String addAdmin(@RequestBody Admin admin) {
		if (adminService.findAdminByName(admin.getUsername()) != null) {
			return "用户名已存在";
		}
		adminService.addAdmin(admin);
		return "success";
	}

	@RequestMapping(value = "admin/{username}/{password}", method = RequestMethod.GET)
	public String findAdmin(@PathVariable String username,
			@PathVariable String password, HttpSession session) {
		Admin realAdmin = adminService.findAdminByName(username);
		if (realAdmin != null && realAdmin.getPassword().equals(password)) {
			session.setAttribute("qx", realAdmin.getQx()+"");
			return "success";
		}

		return "用户名密码不正确";
	}

	@RequestMapping(value = "admin/{username}", method = RequestMethod.GET)
	public Admin findAdminByUsername(@PathVariable String username) {
		return adminService.findAdminByName(username);
	}

	@RequestMapping(value = "admin/{id}", method = RequestMethod.DELETE)
	public void deleteAdmin(@PathVariable int id) {
		adminService.deleteAdmin(id);
	}

	@RequestMapping(value = "admin", method = RequestMethod.PUT)
	public String updateAdmin(@RequestBody Admin admin) {
		adminService.updateAdmin(admin);

		return "success";
	}

}
